package com.tekj.cxqcb.view.user;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tekj.cxqcb.MainBActivity;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.AppLoginBean;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.VersionBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import common.base.MainApplication;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.plugins.tbs.WebCoreAction;
import common.tool.AppUpdateManager;
import common.tool.PUB;
import common.widget.GetBtnCodeView;
import es.dmoral.toasty.Toasty;


/**
 * 登陆
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.username_edt)
    EditText usernameEdt;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.password_edt)
    EditText passwordEdt;
    @BindView(R.id.login_btn)
    TextView loginBtn;
    @BindView(R.id.img_islook)
    ImageView imgIslook;
    @BindView(R.id.tv_terms)
    TextView tvTerms;
    //    @BindView(R.id.img_load)
//    ImageView imgLoad;
    String userid;
    String token;
    private BusinessDao businessDao;
    private List<String> list;
    private AppUpdateManager appUpdateManager;

    @Override
    public void init() {
        imgBack.setVisibility(View.INVISIBLE);
        tvTitle.setText("");
        String mobile = PUB.SharedPreferences(this, "mobile", "#read");
        usernameEdt.setText(mobile);
        businessDao = new BusinessDao(this, this);
        list = new ArrayList<>();
        list.add("https://cars-cxqc.com/static/dist/index.html#/agreement1");
        list.add("https://cars-cxqc.com/static/dist/index.html#/agreement");

        setTextColor(new SpannableStringBuilder(),
                "我已阅读并同意《车享其成用户协议》及《隐私政策》",
                new int[]{7, 18}, new int[]{17, 24}, list, tvTerms);

        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_NOTIFICATION_POLICY,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_LOGS,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    /*  Manifest.permission.SET_DEBUG_APP,
                 Manifest.permission.SYSTEM_ALERT_WINDOW,
                Manifest.permission.GET_ACCOUNTS,
                  Manifest.permission.WRITE_APN_SETTINGS*/};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }

//        businessDao.GetAppVersion();
//        RequestOptions options = new RequestOptions()
//                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
//        Glide.with(activity).load(R.mipmap.ico_load).apply(options).into(imgLoad);

        userid = PUB.SharedPreferences(activity, "userid", "#read");
        token = PUB.SharedPreferences(activity, "token", "#read");
        SilenceLogin();
    }

    @Override
    public int setLayout() {
        return R.layout.activity_loogin;
    }

    @Override
    public void initLoadStart() {

    }

    @Override
    public void initLoadEnd() {

    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 短信验证码:
                PubStatusBean bean = (PubStatusBean) bindingViewBean.getBean();
                if ("0000000".equals(bean.getCode())) {
                    GetBtnCodeView mGetBtnCodeView = new GetBtnCodeView(tvSendCode, 60000, 1000);
                    mGetBtnCodeView.start();
                    Toasty.success(this, bean.getMsg()).show();
                } else
                    Toasty.error(this, bean.getMsg()).show();
                break;

            case 登陆:
                AppLoginBean appLoginBean = (AppLoginBean) bindingViewBean.getBean();
                if ("0000000".equals(appLoginBean.getCode())) {
                    PUB.SharedPreferences(this, "mobile", usernameEdt.getText().toString().trim());
                    PUB.SharedPreferences(activity, "userid", appLoginBean.getData().getUserId());
                    PUB.SharedPreferences(activity, "token", appLoginBean.getData().getToken());

                    MainApplication.UserToken = appLoginBean.getData().getToken();

                    Intent intent = new Intent(activity, MainBActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", appLoginBean.getData());
                    intent.putExtra("data", bundle);
                    startActivity(intent);
                    finish();
                    Toasty.success(this, "登陆成功").show();
                } else {
                    Toasty.error(this, appLoginBean.getMsg()).show();
                }

                break;

            case 更新信息:
                VersionBean versionBean = (VersionBean) bindingViewBean.getBean();
                if (!versionBean.getCode().equals("0000000")) {
                    return;
                }
                appUpdateManager = new AppUpdateManager(activity, false, versionBean.getData());
                appUpdateManager.checkUpdate();
                break;
            case 登陆2:
                AppLoginBean appLoginBean2 = (AppLoginBean) bindingViewBean.getBean();
                if ("0000000".equals(appLoginBean2.getCode())) {

                    MainApplication.UserToken = token;

                    Intent intent = new Intent(activity, MainBActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", appLoginBean2.getData());
                    intent.putExtra("data", bundle);
                    startActivity(intent);
                    finish();
                    Toasty.success(this, "登陆成功").show();
                } else {
                    Toasty.error(this, appLoginBean2.getMsg()).show();
                }
                break;

            case Token过期:
                Intent intent = new Intent(activity, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }

    }

    boolean isLook = true;

    @OnClick({R.id.tv_send_code, R.id.login_btn, R.id.ll_back, R.id.img_islook})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_send_code:
                if (usernameEdt.getText().toString().trim().equals("")) {
                    Toasty.warning(this, "请先填写手机号").show();
                    return;
                }
                businessDao.SendCode(usernameEdt.getText().toString().trim());
                break;
            case R.id.login_btn:
                if (usernameEdt.getText().toString().trim().equals("")) {
                    Toasty.warning(this, "请先填写手机号").show();
                    return;
                }
                if (passwordEdt.getText().toString().trim().equals("")) {
                    Toasty.warning(this, "请填写验证码").show();
                    return;
                }
                if (!isLook) {
                    Toasty.warning(this, "请先阅读用户协议").show();
                    return;
                }
                businessDao.AppLogin(usernameEdt.getText().toString(), passwordEdt.getText().toString());
                break;
            case R.id.ll_back:
                finish();
                break;

            case R.id.img_islook:
                isLook = !isLook;
                imgIslook.setImageResource(isLook ? R.mipmap.icon_j_select : R.mipmap.img_wgx);
                break;
        }
    }


    //    设置部分文字点击事件
    public void setClickableSpan(SpannableStringBuilder style, int start, int end, final String url) {
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                new WebCoreAction(activity, url + "&token=" + MainApplication.UserToken);
//                Toasty.normal(IntegralGuaranteeActivity.this, "1").show();
            }
        };
        style.setSpan(clickableSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        //设置部分文字颜色
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#3296fa"));
        style.setSpan(foregroundColorSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }

    /**
     * 设置各个变色文字的点击事件
     *
     * @param style
     * @param content
     * @param start
     * @param end
     * @param urls
     */
    public void setTextColor(SpannableStringBuilder style,
                             String content,
                             int[] start, int[] end,
                             List<String> urls,
                             TextView textView) {
        style.append(content);
        for (int i = 0; i < start.length; i++) {
            setClickableSpan(style, start[i], end[i], urls.get(i));
        }
        //配置给TextView
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setText(style);
        textView.setHighlightColor(getResources().getColor(R.color.transparent));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 101:
                    appUpdateManager.checkIsAndroidO();
                    break;
            }
        }
    }

    boolean isSilenceLogin;

    void SilenceLogin() {
        isSilenceLogin = false;
        if (token != null && !token.equals("")) {
            businessDao.selectUserById(userid);
        }
    }
}
